package com.gitee.cirnochat.common.event.listener;


import com.gitee.cirnochat.common.event.UserEvent;
import com.gitee.cirnochat.common.event.UserEventFactory;
import com.gitee.cirnochat.login.model.enums.DeviceType;
import com.gitee.cirnochat.user.model.enums.UserStatus;
import com.gitee.cirnochat.websocket.service.manager.SessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.Map;


@Slf4j
@Component
@RequiredArgsConstructor
public class WebSocketDisconnectListener implements ApplicationListener<SessionDisconnectEvent> {
    private final SessionManager sessionManager;
    private final StringRedisTemplate redisTemplate;
    private final ApplicationEventPublisher eventPublisher;

    @EventListener
    public void handleSessionDisconnect(SessionDisconnectEvent event) {
        Principal user = event.getUser();
        Message<byte[]> message = event.getMessage();
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (user != null && accessor != null) {
            log.info("WebSocket 断开连接，用户ID: {}", user.getName());
            Map<String, Object> sessionAttributes = accessor.getSessionAttributes();
            // 从会话属性中获取设备信息
            String deviceId = (String) sessionAttributes.get("deviceId");
            DeviceType deviceType = DeviceType.fromValue(Integer.valueOf((String) sessionAttributes.get("deviceType")));
            String deviceName = (String) sessionAttributes.get("deviceName");
            Long userId = Long.parseLong(user.getName());
            // 创建事件
            UserEvent userEvent = UserEventFactory.createUserEvent(event.getSource(), userId, UserStatus.OFFLINE,deviceId, deviceName, deviceType);
            // 离线状态后，发布消息推送事件
            eventPublisher.publishEvent(userEvent);
            // 注销用户设备
            sessionManager.unregister(userId, deviceType);
        }
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {}
}
